/**
 * Copyright (c) 快宝网络 kuaidihelp.com Co., Ltd. All Rights Reserved 禁止外泄以及用于其它的商业用途
 */

/* eslint-disable radix */
/* eslint-disable array-callback-return */
/* eslint-disable no-plusplus */
import { message, Modal } from 'antd';
import { isArray, isEmptyObject } from '@/utils/isSomeType';
import { isLegalData, saveCookie, getCookie, getLStorage } from '@/utils/utils';
import {
  zyGetCompaniesList, // 中邮获取公司列表
  zyGetProvinces,
  zyGetCities,
} from '@/services/zyAcount';
import { isEmpty } from 'lodash';
import { changePostName } from '../utils/changePostCompanyName';
import {
  getAllView,
  getPostList,
  deleteOption,
  openService,
  setScanOption,
  correctOption,
  addOption,
  getScanSearch,
  getChartsView,
  getBranchInfo,
  getCode,
  getTabList,
  getKanBanList,
  getKanBanOperatorList,
  kanBanResend,
  getSetList,
  deletSetList,
  addSetList,
  getCompanyInfoByBranchCode,
  getDeviceNumberList,
  saveDeviceNumber,
  saveDeviceNumberForZt,
  deleteDeviceNumber,
  getGunType,
  getRegisterCodeInfoList,
  deduction, // 扣费设置
  getUserInfo, // 获取用户费用设置信息
  checkStoGunAccount,
  getShortMessage,
  stoCheckPhone,
  getAuthManagementList,
  changeAuth,
  deleteDeviceNumberForZt,
  getDeviceNumberListForZt,
  getGpAuthListByBrand,
  saveDeviceNumberForYt,
  getJtTaskNumber,
  setJtTaskNumber,
} from '../services/allocation';

export default {
  namespace: 'allocation',

  state: {
    visible: false,
    overViewStatus: [],
    oneOption: {},
    postList: [],
    setList: [],
    prevList: [], // 上一站数据列表
    nextList: [], // 下一站
    gunNubmerList: [{}],
    tabList: [],
    kanBanList: {
      list: [],
    },
    operatorList: [],
    gunRegisterList: [], // 巴枪注册列表
    registerCodeInfoList: [], // 中通巴枪注册工号下拉信息
    gunType: [], // 申通巴枪设备型号
    deductionInfo: {}, // 扣费信息
    stoAccountInfo: {}, // 申通巴枪账号校验信息
    authManagementList: {},
    provinceList: [],
    cityList: [],
    addressList: [],
    allBranchInfo: {}, // 所有网点信息
    ztGunRegisterList: [], // 中通巴枪设备编号列表
    todayViewData: [], // 今日数据总览
  },

  effects: {
    // 获取巴枪扫描配置列表数据
    *getPostList({ payload = {} }, { call, put, select }) {
      const { user_info, gp_area_ids = [], area_ids } = yield select(
        ({ info: { companyData } = {} } = {}) => companyData,
      );
      const { realAccount, phone, user_type } = user_info;
      if (user_type == 1) {
        const isCompany = area_ids == '*';
        const cacheAreaId = getLStorage(`KB_GP_AREA_${phone}`);
        const area_id = gp_area_ids.includes(cacheAreaId)
          ? cacheAreaId
          : isCompany
            ? '0'
            : gp_area_ids[0];
        payload.area_id = area_id;
      }
      const fakeAccount = realAccount == 2;
      const response = yield call(getPostList, payload);
      const { code, data, msg } = response;
      if (code == 0 && data) {
        let htExist = null;
        let ytExist = null;
        data.forEach(item => {
          item.type = item.brand;
          item.brand == 'ht' && (htExist = true);
          item.brand == 'yt' && (ytExist = true);
          item.brand_name = item.brand;
          item.brand = changePostName(item.brand);
        });
        // 假账号过滤
        const list = !fakeAccount ? data : data.filter(v => !['yd', 'yt'].includes(v.brand_name));
        yield put({
          type: 'save',
          payload: {
            postList: list,
            htExist,
            ytExist,
          },
        });
      } else {
        message.warning(msg);
      }
    },
    // 删除单条配置
    *deleteOption({ payload }, { call, put }) {
      const response = yield call(deleteOption, payload);
      const { code, data, msg } = response;
      if (code == 0 && data) {
        yield put({
          type: 'getPostList',
        });
        message.success('删除成功');
      } else {
        message.warning(msg);
      }
    },
    // 开启/关闭服务
    *openService({ payload }, { call, put }) {
      const response = yield call(openService, payload);
      const { code, data, msg } = response;
      if (code == 0 && data) {
        yield put({
          type: 'getPostList',
        });
        message.success('操作成功');
      } else {
        message.warning(msg);
      }
    },
    // 巴枪设备编号添加、删除, 上一站添加，删除（除申通外）
    *setScanOption({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(setScanOption, payload);
      const { code, data, msg } = response;
      if (code == 0 && data) {
        yield put({
          type: 'save',
          payload: {
            visible: false,
            type: '',
          },
        });
        // yield put({
        //   type: "getPostList",
        // });
        message.success('成功');
        __dva_resolve(response);
      } else {
        message.warning(msg);
        __dva_reject(response);
      }
    },
    // 添加单条公司信息
    *addOption({ payload }, { call, put }) {
      const response = yield call(addOption, payload);
      const { code, data, msg } = response;
      if (code == 0 && data) {
        yield put({
          type: 'getPostList',
        });
        yield put({
          type: 'save',
          payload: {
            visible: false,
            type: null,
          },
        });
        message.success('操作成功');
      } else {
        message.warning(msg);
      }
    },
    // 修改单条公司信息
    *correctOption({ payload }, { call, put }) {
      const response = yield call(correctOption, payload);
      const { code, data, msg } = response;
      if (code == 0 && data) {
        yield put({
          type: 'save',
          payload: {
            visible: false,
            type: null,
          },
        });
        yield put({
          type: 'save',
          payload: {
            postList: [],
          },
        });
        yield put({
          type: 'getPostList',
        });
        message.success('操作成功');
      } else {
        message.warning(msg);
      }
    },
    // 获得扫描记录的搜索
    *getScanSearch({ payload }, { call, put }) {
      const response = yield call(getScanSearch, payload);
      const { n_export } = payload || {};
      const { code, data, msg } = response;
      if (code == 0 && data) {
        if (n_export) {
          Modal.info({
            title: '温馨提示',
            content: '导出数据申请已提交，请至【报表下载】处下载',
          });
          return;
        }
        data.list.forEach((item, index) => {
          item.id = index;
          item.brand_name = item.brand;
          item.brand = changePostName(item.brand);
          Object.keys(item).forEach(keys => {
            if (keys == 'send_status') {
              switch (item[keys]) {
                case '1':
                  item[keys] = '已推送';
                  break;
                default:
                  item[keys] = '未推送';
                  break;
              }
            }
          });
        });
        switch (payload.waybill_type) {
          case 5:
            yield put({
              type: 'save',
              payload: {
                arriveScanTableData: {
                  list: data.list,
                  total: data.ct,
                  page: payload.page,
                },
              },
            });
            break;
          case 2:
            yield put({
              type: 'save',
              payload: {
                deliveryScanTableData: {
                  list: data.list,
                  total: data.ct,
                  page: payload.page,
                },
              },
            });
            break;
          case 3:
            yield put({
              type: 'save',
              payload: {
                signScanTableData: {
                  list: data.list,
                  total: data.ct,
                  page: payload.page,
                },
              },
            });
            break;
          case 4:
            yield put({
              type: 'save',
              payload: {
                errorScanTableData: {
                  list: data.list,
                  total: data.ct,
                  page: payload.page,
                },
              },
            });
            break;
          case 6:
            yield put({
              type: 'save',
              payload: {
                sendScanTableData: {
                  list: data.list,
                  total: data.ct,
                  page: payload.page,
                },
              },
            });
            break;
          default:
            break;
        }
      } else {
        message.warning(msg);
      }
    },

    // 获取数据总览
    *getAllView({ payload }, { call, put, select }) {
      // 是否可以请求的标志
      const canGetTodayAllView = !getCookie('canGetTodayAllView');
      const { allViewData, tabAllType, search } = yield select(_ => _.allocation);
      let todayViewData = '';
      try {
        todayViewData = JSON.parse(localStorage.getItem('todayViewData'));
      } catch (error) {
        console.log('error', error);
      }
      const { time } = payload;
      // 今日数据的请求频率限制，一分钟一次
      if (time == 0) {
        if (canGetTodayAllView) {
          saveCookie('canGetTodayAllView', false, 60);
        } else {
          yield put({
            type: 'save',
            payload: {
              tabAllType: payload.time,
              allViewData: todayViewData,
            },
          });
          return;
        }
      }
      // 判断有没有数据，没有数据，请求。如果有数据，参数是否一致，若一致拦截。
      if (allViewData) {
        if (time == tabAllType && !search) return;
      }
      const response = yield call(getAllView, payload);
      const { code, data, msg } = response;
      if (code == 0 && data) {
        const type =
          time == 0
            ? ['arrival', 'notArrival', 'delivery', 'notDelivery', 'sign', 'notSign']
            : ['arrival', 'delivery', 'sign'];
        const postType = ['zt', 'sto', 'yt', 'tt', 'ht', 'yd', 'jt', 'zykd', 'ems', 'fw'];
        const all =
          time == 0
            ? {
                arrival: null,
                notArrival: null,
                delivery: null,
                notDelivery: null,
                sign: null,
                notSign: null,
              }
            : { arrival: null, delivery: null, sign: null };
        const list = [];

        if (time == 0) {
          type.map(item => {
            if (item != 'proportion') {
              postType.map(postSing => {
                const postType = data[postSing];
                if (postSing == 'all') return;
                if (postType) {
                  if (item == 'arrival') {
                    postType.arrival.success = parseInt(postType.arrival.success);
                    all[item] += parseInt(postType.arrival.success);
                  } else if (item == 'notArrival') {
                    postType.arrival.failed = parseInt(postType.arrival.failed);
                    all[item] += parseInt(postType.arrival.failed);
                  } else if (item == 'delivery') {
                    postType.delivery.success = parseInt(postType.delivery.success);
                    all[item] += parseInt(postType.delivery.success);
                  } else if (item == 'notDelivery') {
                    postType.delivery.failed = parseInt(postType.delivery.failed);
                    all[item] += parseInt(postType.delivery.failed);
                  } else if (item == 'sign') {
                    postType.sign.success = parseInt(postType.sign.success);
                    all[item] += parseInt(postType.sign.success);
                  } else if (item == 'notSign') {
                    postType.sign.failed = parseInt(postType.sign.failed);
                    all[item] += parseInt(postType.sign.failed);
                  }
                } else {
                  data[postSing] = {
                    arrival: {
                      failed: 0,
                      success: 0,
                    },
                    delivery: {
                      failed: 0,
                      success: 0,
                    },
                    sign: {
                      failed: 0,
                      success: 0,
                    },
                  };
                }
              });
              if (!all[item]) {
                all[item] = 0;
              }
            }
          });
          data.all = all;
          type.map((item, index) => {
            const tr = {};
            tr.id = index;
            item == 'arrival' && (tr.title = '到件已推送');
            item == 'notArrival' && (tr.title = '到件未推送');
            item == 'delivery' && (tr.title = '派件已推送');
            item == 'notDelivery' && (tr.title = '派件未推送');
            item == 'sign' && (tr.title = '签收已推送');
            item == 'notSign' && (tr.title = '签收未推送');
            // item == "proportion" && (tr.title = "占比");
            Object.keys(data).map(postSing => {
              const postType = data[postSing];
              if (postSing == 'all') {
                if (item == 'arrival') {
                  tr.all = data.all.arrival;
                } else if (item == 'notArrival') {
                  tr.all = data.all.notArrival;
                } else if (item == 'delivery') {
                  tr.all = data.all.delivery;
                } else if (item == 'notDelivery') {
                  tr.all = data.all.notDelivery;
                } else if (item == 'sign') {
                  tr.all = data.all.sign;
                } else if (item == 'notSign') {
                  tr.all = data.all.notSign;
                }
              } else if (item == 'arrival') {
                tr[postSing] = postType.arrival.success;
              } else if (item == 'notArrival') {
                tr[postSing] = postType.arrival.failed;
              } else if (item == 'delivery') {
                tr[postSing] = postType.delivery.success;
              } else if (item == 'notDelivery') {
                tr[postSing] = postType.delivery.failed;
              } else if (item == 'sign') {
                tr[postSing] = postType.sign.success;
              } else if (item == 'notSign') {
                tr[postSing] = postType.sign.failed;
              }
            });
            list.push(tr);
          });
          yield put({
            type: 'save',
            payload: {
              todayViewData: list,
              tabAllType: payload.time,
            },
          });
          // 缓存今日数据
          localStorage.setItem('todayViewData', JSON.stringify(list));
        } else {
          // 数据格式处理
          postType.map(item => {
            !data[item] && (data[item] = {});
          });

          type.map(item => {
            if (item != 'proportion') {
              postType.map(postSing => {
                if (postSing == 'all') return;
                if (data[postSing][item]) {
                  data[postSing][item] = parseInt(data[postSing][item]);
                  all[item] += parseInt(data[postSing][item]);
                } else {
                  data[postSing][item] = 0;
                }
              });
              if (!all[item]) {
                all[item] = 0;
              }
            }
          });
          data.all = all;
          type.map((item, index) => {
            const tr = {};
            tr.id = index;
            item == 'arrival' && (tr.title = '到件数量');
            item == 'delivery' && (tr.title = '派件数量');
            item == 'sign' && (tr.title = '签收数量');
            // item == "proportion" && (tr.title = "占比");
            Object.keys(data).map(postSing => {
              if (item != 'proportion') {
                tr[postSing] = data[postSing][item];
              }
            });
            list.push(tr);
          });
        }

        yield put({
          type: 'save',
          payload: {
            allViewData: list,
            tabAllType: payload.time,
          },
        });
      } else {
        message.warning(msg);
      }
    },
    // 获取近30天趋势图数据
    *getChartsView({ payload }, { call, put, select }) {
      const {
        arriveOriginData,
        sendOriginData,
        signOriginData,
        tabArriveType,
        tabSendType,
        tabSignType,
        search,
      } = yield select(_ => _.allocation);
      /**
       * 趋势图只请求一次接口，并把数据存为原始数据，保存下来。
       * 需要用的数据是要通过方法去转换
       * 切换tab时，调用接口，有数据就拦截请求，并把原始数据按照payload的参数改变一份即可
       * search 判断是否查询
       */
      if (payload.waybill_type == 5 && arriveOriginData && !search) {
        if (payload.brand == tabArriveType) return;
        yield put({
          type: 'save',
          payload: {
            arriveData: changeData(arriveOriginData, payload.brand),
            tabArriveType: payload.brand,
          },
        });
        return;
      }
      if (payload.waybill_type == 2 && sendOriginData && !search) {
        if (payload.brand == tabSendType) return;
        yield put({
          type: 'save',
          payload: {
            sendData: changeData(sendOriginData, payload.brand),
            tabSendType: payload.brand,
          },
        });
        return;
      }
      if (payload.waybill_type == 3 && signOriginData && !search) {
        if (payload.brand == tabSignType) return;
        yield put({
          type: 'save',
          payload: {
            signData: changeData(signOriginData, payload.brand),
            tabSignType: payload.brand,
          },
        });
        return;
      }

      const response = yield call(getChartsView, payload);
      const { code, data, msg } = response;
      if (code == 0 && data) {
        // 计算出趋势图全部按钮的数据
        const newData = JSON.parse(JSON.stringify(data));
        const list = new Set();
        let dataAll = [];
        Object.keys(newData).map(item => {
          dataAll = [...dataAll, ...newData[item]];
          newData[item].map(items => {
            list.add(items.dt);
          });
        });

        const arrShow = (function insertionSort(array) {
          if (Object.prototype.toString.call(array).slice(8, -1) === 'Array') {
            for (let i = 1; i < array.length; i++) {
              const key = array[i];
              let j = i - 1;
              while (j >= 0 && array[j] > key) {
                array[j + 1] = array[j];
                j--;
              }
              array[j + 1] = key;
            }
            return array;
          }
          console.info('趋势图数据处理错误');
          return [];
        })(Array.from(list));

        const allList = [];
        arrShow.forEach(item => {
          const one = { dt: '', nbs: 0 };
          dataAll.map(items => {
            if (item == items.dt) {
              one.dt = item;
              one.nbs += parseInt(items.nbs);
            }
          });
          allList.push(one);
        });
        newData.all = allList;

        if (payload.waybill_type == 5) {
          yield put({
            type: 'save',
            payload: {
              arriveOriginData: newData,
              arriveData: changeData(newData, payload.brand),
              tabArriveType: payload.brand,
            },
          });
        } else if (payload.waybill_type == 2) {
          yield put({
            type: 'save',
            payload: {
              sendOriginData: newData,
              sendData: changeData(newData, payload.brand),
              tabSendType: payload.brand,
            },
          });
        } else if (payload.waybill_type == 3) {
          yield put({
            type: 'save',
            payload: {
              signOriginData: newData,
              signData: changeData(newData, payload.brand),
              tabSignType: payload.brand,
            },
          });
        }
      } else {
        message.warning(msg);
      }
      function changeData(source, type) {
        const data = [];
        source[type] &&
          source[type].map(item => {
            const obj = {};
            obj.dt = item.dt.substring(5);
            obj.nbs = parseInt(item.nbs);
            data.push(obj);
          });
        return data;
      }
    },
    // 获取网点信息
    *getBranchInfo({ payload }, { call, put }) {
      const { waybill_type, ...rest } = payload;
      const response = yield call(getBranchInfo, rest);
      if (isEmpty(response)) return;
      const { code, data, msg } = response;
      if (code == 0) {
        if (data) {
          // 增加全部选项
          data.length == 0 && data == {};
          let brandCode = [];
          Object.keys(data).forEach(item => {
            brandCode = Array.from(new Set([...brandCode, ...data[item]]));
            data[item].unshift('all');
          });
          brandCode.length != 0 && brandCode.unshift('all');
          data.all = brandCode;
          if (!payload.waybill_type) {
            yield put({
              type: 'save',
              payload: {
                allBranchInfo: data,
              },
            });
          } else {
            yield put({
              type: 'save',
              payload: {
                [`${waybill_type}BranchInfo`]: data,
              },
            });
          }
        }
      } else {
        message.warning(msg);
      }
    },
    // 获取验证码
    *getCode({ payload, then = () => {} }, { call }) {
      const response = yield call(getCode, payload);
      const { code, msg } = response;
      if (code > 0) {
        message.error(msg);
        return;
      }
      message.success(msg);
      then();
    },
    // 获取上一站、下一站设置列表
    *getSetList({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(getSetList, payload);
      if (!response) return;
      const { code, data, msg } = response;
      const list = isArray(data) ? data : [];

      const params = payload.station_type == '1' ? { nextList: list } : { prevList: list }; // 1：下一站，2：上一站

      if (code == 0) {
        yield put({
          type: 'save',
          payload: params,
        });
        __dva_resolve(response);
      } else {
        __dva_reject();
        message.error(msg);
      }
    },
    // 下一站设置列表，删除
    *deletSetList({ payload, __dva_resolve, __dva_reject }, { call }) {
      const response = yield call(deletSetList, payload);

      if (!response) return;
      const { code, msg } = response;

      if (code == 0) {
        message.success(msg);
        __dva_resolve(response);
      } else {
        __dva_reject();
        message.error(msg);
      }
    },
    // 下一站设置列表，添加
    *addSetList({ payload, __dva_resolve, __dva_reject }, { call }) {
      const response = yield call(addSetList, payload);

      if (!response) return;
      const { code, msg } = response;

      if (code == 0) {
        message.success(msg);
        __dva_resolve(response);
      } else {
        __dva_reject();
        message.error(msg);
      }
    },
    // 业务员看板，获取tab列表
    *getTabList({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(getTabList, payload);
      if (!response) return;
      const { code, data, msg } = response;

      if (code == 0) {
        if (isLegalData(data, []).length == 0) {
          message.warning('暂无品牌数据');
        }
        yield put({
          type: 'save',
          payload: {
            tabList: isLegalData(data, []),
          },
        });
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        message.error(msg);
      }
    },
    // 业务员看板，获取表格列表
    *getKanBanList({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(getKanBanList, payload);
      const { n_export } = payload;
      if (!response) return;
      const { code, data, msg } = response;
      const { list, ct, page, pageSize } = data;

      if (code == 0) {
        if (n_export) {
          Modal.info({
            title: '温馨提示',
            content: '导出数据申请已提交，请至【报表下载】处下载',
          });
        } else {
          yield put({
            type: 'save',
            payload: {
              kanBanList: {
                list: isLegalData(list, []), // 防止后端传递空对象
                pagination: {
                  total: ct,
                  pageSize,
                  current: page,
                  showQuickJumper: false,
                  showSizeChanger: false,
                },
              },
            },
          });
        }
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        message.error(msg);
      }
    },
    // 业务员看板，获取下拉框列表
    *getKanBanOperatorList({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(getKanBanOperatorList, payload);
      if (!response) return;
      const { code, data, msg } = response;
      const { list } = data;

      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            operatorList: list,
          },
        });
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        message.error(msg);
      }
    },
    // 业务员看板，重传未推送数据
    *kanBanResend({ payload, __dva_resolve, __dva_reject }, { call }) {
      const response = yield call(kanBanResend, payload);
      if (!response) return;
      const { code } = response;
      if (code == 0) {
        message.success('提交成功！');
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        message.error('提交失败！');
      }
    },
    // 上一站信息及巴枪设备编号
    *getCompanyInfoByBranchCode({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(getCompanyInfoByBranchCode, payload);

      if (!response) return;
      const { code, data, msg } = response;
      const list =
        data.length > 0 && !isEmptyObject(data[0]) && data[0].previous_station_name
          ? [
              {
                branch_code: data[0].branch_code,
                brand: data[0].brand,
                create_time: data[0].create_time,
                id: data[0].id,
                kb_id: data[0].kb_id,
                station_code: data[0].previous_station_code,
                station_name: data[0].previous_station_name,
                // station_type: data[0].station_type,
                update_time: data[0].update_time,
              },
            ]
          : [];

      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            prevList: list,
            gunNubmerList: data,
          },
        });
        __dva_resolve(response);
      } else {
        __dva_reject();
        message.error(msg);
      }
    },
    // 上一站信息及巴枪设备编号
    *getDeviceNumberList({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(getDeviceNumberList, payload);

      if (!response) return;
      const { code, data, msg } = response;

      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            gunRegisterList: isLegalData(data, []),
          },
        });
        __dva_resolve(response);
      } else {
        __dva_reject();
        message.error(msg);
      }
    },
    // 中通获取巴枪设备编号
    *getDeviceNumberListForZt({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(getDeviceNumberListForZt, payload);

      if (!response) return;
      const { code, data, msg } = response;

      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            ztGunRegisterList: isLegalData(data, []),
          },
        });
        __dva_resolve(response);
      } else {
        __dva_reject();
        message.error(msg);
      }
    },
    // 中通巴枪注册，发起注册
    *saveDeviceNumber({ payload, __dva_resolve, __dva_reject }, { call }) {
      const response = yield call(saveDeviceNumber, payload);
      if (!response) return;
      const { code } = response;
      if (code == 0) {
        message.success('添加成功！');
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        message.error('提交失败！');
      }
    },
    // 中通添加设备编号
    *saveDeviceNumberForZt({ payload, __dva_resolve, __dva_reject }, { call }) {
      const response = yield call(saveDeviceNumberForZt, payload);
      if (!response) return;
      const { code } = response;
      if (code == 0) {
        message.success('添加成功！');
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        message.error('提交失败！');
      }
    },
    // 中通巴枪注册，删除未通过或通过的审核记录
    *deleteDeviceNumber({ payload, __dva_resolve, __dva_reject }, { call }) {
      const response = yield call(deleteDeviceNumber, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        message.success(msg);
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        message.error('删除失败！');
      }
    },
    // 中通巴枪注册，删除未通过或通过的审核记录
    *deleteDeviceNumberForZt({ payload, __dva_resolve, __dva_reject }, { call }) {
      const response = yield call(deleteDeviceNumberForZt, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        message.success(msg);
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        message.error('删除失败！');
      }
    },
    // 中通巴枪注册，工号信息下拉数据
    *getRegisterCodeInfoList({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(getRegisterCodeInfoList, payload);
      if (!response) return;
      const { code, data, msg } = response;
      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            registerCodeInfoList: isLegalData(data, []),
          },
        });
        __dva_resolve(response);
      } else {
        yield put({
          type: 'save',
          payload: {
            registerCodeInfoList: [],
          },
        });
        __dva_reject(response);
        message.error(msg);
      }
    },
    // 申通、中通获取巴枪型号
    *getGunType({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(getGunType, payload);
      if (!response) return;
      const { code, data, msg } = response;
      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            gunType: isLegalData(data, []),
          },
        });
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        message.error(msg);
      }
    },
    // 巴枪扫描配置，获取用户扣费信息
    *getUserInfo({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(getUserInfo, payload);
      if (!response) return;
      const { code, data, msg } = response;
      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            deductionInfo: isLegalData(data, {}),
          },
        });
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        message.error(msg);
      }
    },
    // 巴枪扫描配置，扣费设置
    *deduction({ payload, __dva_resolve, __dva_reject }, { call }) {
      const response = yield call(deduction, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        message.success(msg);
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        message.error(msg);
      }
    },
    // 巴枪扫描配置，校验申通巴枪账号是否存在
    *checkStoGunAccount({ payload, __dva_resolve }, { call, put }) {
      const response = yield call(checkStoGunAccount, payload);
      if (!response) return;
      const { code, data, msg } = response;
      if (code == 1013) {
        // 工号存在但是需要发送短信校验
        yield put({
          type: 'save',
          payload: {
            stoAccountInfo: {
              phone: data,
              message: '',
            },
          },
        });
        __dva_resolve(response);
      } else if (code == 0) {
        // 校验通过
        __dva_resolve(response);
      } else {
        // 工号不存在
        yield put({
          type: 'save',
          payload: {
            stoAccountInfo: {
              message: msg,
              phone: '',
            },
          },
        });
        __dva_resolve(response);
      }
    },
    // 巴枪扫描配置，添加申通巴枪账号，获取短信验证码
    *getShortMessage({ payload, __dva_resolve, __dva_reject }, { call }) {
      const response = yield call(getShortMessage, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        message.success(msg);
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        message.error(msg);
      }
    },
    // 巴枪扫描配置，添加申通巴枪账号，校验手机号
    *stoCheckPhone({ payload, __dva_resolve, __dva_reject }, { call }) {
      const response = yield call(stoCheckPhone, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        message.success(msg);
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        message.error(msg);
      }
    },
    // 共配权限管理，获取列表
    *getAuthManagementList({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(getAuthManagementList, payload);
      if (!response) return;
      const { code, data, msg } = response;
      const { list, page, count } = data;
      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            authManagementList: {
              list: isLegalData(list, []),
              pagination: {
                total: count,
                pageSize: 20,
                current: page,
                showQuickJumper: false,
                showSizeChanger: false,
              },
            },
          },
        });
        __dva_resolve(response);
      } else {
        message.error(msg);
        __dva_reject(response);
      }
    },
    // 共配权限，修改共配权限
    *changeAuth({ payload, __dva_resolve, __dva_reject }, { call }) {
      const response = yield call(changeAuth, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code == 0) {
        message.success(msg);
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        message.error(msg);
      }
    },
    // 共配权限管理，获取不同品牌的共配权限
    *getGpAuthListByBrand({ payload, __dva_resolve, __dva_reject }, { call }) {
      const response = yield call(getGpAuthListByBrand, payload);
      if (!response) return;
      const { code, data = [], msg } = response;
      if (code == 0) {
        __dva_resolve(isLegalData(data));
      } else {
        __dva_reject(response);
        message.error(msg);
      }
    },
    // 共配权限，获取省公司
    *getProvinceList({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(zyGetProvinces, payload);
      if (!response) return;
      const { code, data, msg } = response;
      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            provinceList: isLegalData(data, []),
          },
        });
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        message.error(msg);
      }
    },
    // 共配获取，市公司
    *getCityList({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(zyGetCities, payload);
      if (!response) return;
      const { code, data, msg } = response;
      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            cityList: isLegalData(data, []),
          },
        });
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        message.error(msg);
      }
    },
    *getAddressList({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(zyGetCompaniesList, payload);
      if (!response) return;
      const { code, data, msg } = response;
      if (code == 0) {
        yield put({
          type: 'save',
          payload: {
            addressList: isLegalData(data, []),
          },
        });
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        message.error(msg);
      }
    },
    // 圆通添加设备编号
    *saveDeviceNumberForYt({ payload, __dva_resolve, __dva_reject }, { call }) {
      const response = yield call(saveDeviceNumberForYt, payload);
      if (!response) return;
      const { code } = response;
      if (code == 0) {
        message.success('添加成功！');
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        message.error('提交失败！');
      }
    },
    // 获取极兔任务号列表
    *getJtTaskNumber({ payload, __dva_resolve, __dva_reject }, { call, put }) {
      const response = yield call(getJtTaskNumber, payload);
      if (!response) return;
      const { code, data, msg } = response;
      if (code === 0) {
        const list = isArray(data) ? data : [];
        const formatList = list.map((item, index) => ({ id: index, job_no: item }));
        yield put({
          type: 'save',
          payload: {
            taskList: formatList,
          },
        });
        __dva_resolve(response);
      } else {
        __dva_reject();
        message.error(msg);
      }
    },
    // 设置极兔任务号
    *setJtTaskNumber({ payload, __dva_resolve, __dva_reject }, { call }) {
      const response = yield call(setJtTaskNumber, payload);
      if (!response) return;
      const { code, msg } = response;
      if (code === 0) {
        message.success('操作成功');
        __dva_resolve(response);
      } else {
        __dva_reject(response);
        message.error(msg);
      }
    },
  },

  reducers: {
    save(state, { payload }) {
      return {
        ...state,
        ...payload,
      };
    },
  },
};
